const $ = require('./tool.js');
const common = require('./common.js');
function Xhr(args) {
  args = args || {};
  this.headers = {}
  this.method = 'GET'
  this.url = ''
  this.type = 'json'
  this.responseText = ''
  this.status = ''
  this.readyState = ''
  this.open = function(method, url) {
    this.method = method;
    this.url = url;
  }
  this.requestTask = '';
  this.abort = function() {
    this.requestTask.abort();
  }
  this.send = function(body) {
    var self = this;
    this.requestTask = my.httpRequest({
      url: this.url,
      method: this.method,
      data: body,
      headers: this.headers,
      dataType: 'json',
      complete: function(ret) {
        self.readyState = 4;
        if (ret.data) {
          self.status = ret.statusCode;
          self.responseText = ret.data;
        } else {
          self.responseText = ret;
        }
        if (typeof self.onreadystatechange == 'function') self.onreadystatechange();
      }
    })
  }
  this.setRequestHeader = function(k, v) {
    this.headers[k] = v;
  }
  for (var k in args) this[k] = args[k];
}
$.Storage.setLocalStorage({
  setItem: function(key,data){
    my.setStorageSync({key:key,data:data});
  },
  getItem: function(key){
    var ret = my.getStorageSync({ key });
    return ret && ret.data;
  },
  removeItem: function(key){
    my.removeStorageSync({key});
  },
  clear:my.clearStorageSync
})
my.$ = {
  ...$,
  Xhr,
  computPX:function(n){
    return n * my.getSystemInfoSync().windowWidth / 750;
  },
  platform:'AlipayMiniApp',
  alertx:function(msg,next,args){
    args = args || {};
    my.alert($.merge({
      content: msg || '',
      success: next
    },args))
  },
  confirmx:function(msg,next,args){
    args = args || {};
    my.confirm($.merge({
      content: msg || '',
      success: function(ret){
        if(ret.confirm){
          next(ret);
        }else{
          if(typeof args.cancel === 'function') args.cancel(ret);
        }
      }
    },args))
  },
  styleSheet:function(styles,o){
    return $.string(styles)._eval(o || {});
  },
  location: function() {
    var pages = getCurrentPages();
    pages.pathname = '/' + pages[pages.length - 1].route.split('?')[0];
    return pages.pathname;
  },
  $go: function(url, openType) {
    openType = openType || 'navigateTo';
    openType = openType == 'navigateTo' && getCurrentPages().length >= 5 ? 'redirectTo' : openType;
    if (typeof this[openType] == 'function') this[openType](typeof url == 'object' ? url : { url: url })
  },
  reEnter: function(options) {
    $.Storage.clear(0);
    this.$go(url,'reLaunch');
  },
  ...my,
  App:function(args){
    var _this = this;
    App({
      onError:args.onError,
      onLaunch:function (options) {
        //登录
        $.Storage.set('logined', false, 2);
        var afters = new $.Item();
        afters._push(function (_next) {
          if (args.onLaunch) args.onLaunch(options);
          _next();
        })
        var autoLogin = function (next) {
          if ($.Storage.get('logined')) {
            afters = new $.Item();
            $.Storage.set('logined', false);
          }
          afters._push(function (_next) {
            next();
            _next();
          })
          args.autoLogin(function () {
            $.Storage.set('logined', true);
            afters._do();
          }, function (error) {
            afters = new $.Item();
            if(!$.Storage.get('logined')){
              afters._push(function (_next) {
                if (args.onLaunch) args.onLaunch(options);
                _next();
              })
            }
            _this.reEnter(args.onLogin ? args.onLogin : '/pages/err/err?msg=' + error);
          })
        }
        $.Storage.set('autoLogin', autoLogin);
        //ajax拦截
        if (args.Interceptor) $.Storage.set('loginAction', args.Interceptor, { type: 2 });
      }
    });
  },
  vue: function(args) {
    args = common.call(this, args, 'vue');
    Page({
      data: args.data,
      ...args.methods,
      getData:function(key){
        return this.data[key];
      },
      list: args.list,
      form: args.form,
      classes: args.classes,
      onLoad: function(options) {
        this.options = options;
        args.created && args.created.call(this, options)
      },
      onReady: function() {
        var _this = this;
        if (this.list && this.list.length) {
          this.list.forEach(function (_list) {
            _list.init();
          })
        }
        for (var key in this.classes) if (this.classes[key].init) this.classes[key].init();
        if (args.noLogin || $.Storage.get('logined')){
          if (args.mounted) args.mounted.call(this, this.options);
        }else{
          $.Storage.get('autoLogin')(function(){
            if (args.mounted) args.mounted.call(_this, _this.options);
          })
        }
      },
      onShareAppMessage: function(ret) {
        my.$.correctApp();
        var rc = $.Storage.get('shareAppMessage') || {};
        if (args.methods.onShareAppMessage) $.merge(rc, args.methods.onShareAppMessage.call(this, ret));
        return rc;
      }
    });
  },
  component: function(Component,args) {
    args = common.call(this, args, 'vue');
    var watch = {};
    if (args.props) {
      for (var k in args.props) {
        if(args.props[k].observer) watch[k] = args.props[k].observer;
        args.props[k] = args.props[k].default;
      }
    }
    Component({
      options: { multipleSlots: true },
      props: args.props,
      //data: args.data(),
      methods: { 
        ...args.methods,
        getData:function(key){
          if(this.props && this.props[key] != undefined){
            return this.props[key];
          }else{
            return this.data[key]
          }
        },
        triggerEvent:function(funName,data){
          var first = funName.charAt(0).toUpperCase();
          funName = first + funName.substring(1,funName.length);
          if(this.props['on' + funName]){
            this.props['on' + funName]({detail:data})
          }
        }
      },
      didMount: function() {
        if (typeof args.data == 'function') this.setData(args.data.call(this));
        args.mounted && args.mounted.call(this);
      },
      didUpdate:function(prevProps,prevData){
        for(var key in watch){
          if(prevProps[key] != this.props[key]) watch[key].call(this,this.props[key],prevProps[key]);
        }
      }
    })
  },
  ajax: function(url, callback, args) {
    args = args || {};
    args.xhr = new Xhr();
    var _this = this;
    url = url.replace(new RegExp('^{(.+)}(.+)'),function($0,$1,$2){
      return Y.Storage.get($1) + $2;
    })
    if (url.indexOf('http') != 0) url = $.Storage.get('APIURL') + url;
    args.loading = args.loading || {
      open: function() {
        //my.showLoading({content:'...',delay:5000});
        if (_this.setData) _this.setData({ submiting: true });
      },
      close: function() {
        if (_this.setData) {
          setTimeout(function() {
            //my.hideLoading();
            _this.setData({ submiting: false });
          }, 5000)
        } else {
          //my.hideLoading();
        }
      }
    };
    var ajax = new $.Ajax(url, function(ret){
      if(args.errNotify !== false && ret.errorMsg) {
        my.showToast({
          title: '成功',
          icon: 'none',
          duration: 2000,
          title:ret.errorMsg
        })
      }
      callback(ret);
    }, args);
    ajax.action();
  },
  list: function(args) {
    args = args || {};
    var url = '', getArgs = args.get || '';
    if (typeof getArgs == 'string') {
      url = getArgs;
      getArgs = {};
    } else {
      url = getArgs.url;
      getArgs.url = undefined;
    }
    if(typeof url == 'string'){
      getArgs.xhr = new Xhr();
      url = url.replace(new RegExp('^{(.+)}(.+)'),function($0,$1,$2){
        return Y.Storage.get($1) + $2;
      })
      if (url.indexOf('http') != 0) url = $.Storage.get('APIURL') + url;
      args.get = new $.Ajax(url, '', getArgs);
    }
    return new $.List(args);
  }
}